import axios, {
  AxiosResponse,
  AxiosRequestConfig
} from 'axios';

import { message } from 'antd';

import cookie from 'js-cookie';

import { getStore } from '@/dva';

const expires: number = 6;

const authCode = [401];

const response = (_res_: AxiosResponse) => {
  const {
    data,
    status,
    headers
  } = _res_;
  const { token } = headers;
  const { code = status, data: _data } = data;

  /*强制弹出登录*/
  if (authCode.includes(code)) {
    getStore().dispatch({
      payload: undefined,
      type: 'user/setUserInfo'
    });
    message.error('登录已失效,请重新登录');
  }

  if (token) cookie.set('x_token', token, { expires });
  return code === 200 ? Promise.resolve(_data) : Promise.reject(data);
}

const request = (_req_: AxiosRequestConfig) => {
  const { headers } = _req_;
  const token = cookie.get('x_token');
  if (token) headers['Authorization'] = `Bearer ${token}`;
  return _req_;
}

axios.interceptors.request.use(request);
axios.interceptors.response.use(response);

export default axios;
